//
//  ViewController.swift
//  Duyiguqin
//
//  Created by 张昭 on 2024/7/24.
//

import UIKit
import WebKit
import Alamofire

class HomeViewController: UIViewController {
    
    override func loadView() {
        let v = UIImageView()
        v.image = UIImage(resource: .pageBg)
        v.contentMode = .scaleAspectFill
        v.isUserInteractionEnabled = true
        self.view = v
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setNavigationBarHidden(true, animated: true)
        initializeSubviews()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if App.shared.aboutInfo == nil {
            requestAboutMe()
        }
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(0x0F0F0F)], for: .selected)
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(0xB1B1B1)], for: .normal)
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        naviHeaderView.snp.updateConstraints { make in
            make.height.equalTo(view.safeAreaInsets.top + 44)
        }
    }
    
    private lazy var naviHeaderView: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(resource: .pageBg)
        v.contentMode = .scaleAspectFit
        v.clipsToBounds = true
        v.isUserInteractionEnabled = true
        v.addSubview(tLabel)
        tLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(44)
            make.bottom.equalTo(0)
        }
        return v
    }()
    
    private lazy var tLabel: UILabel = {
        let v = UILabel()
        v.text = "度一古琴"
        v.textColor = UIColor(0x0F0F0F)
        v.font = UIFont.boldSystemFont(ofSize: 18)
        return v
    }()
    
    private lazy var bannerImageView: UIImageView = {
        let v = UIImageView()
        v.clipsToBounds = true
        return v
    }()
        
    private lazy var scrollView: UIScrollView = {
        let v = UIScrollView()
        return v
    }()
    
    private lazy var headerView: UIView = {
        let v = UIView()
        return v
    }()
    
    private lazy var gqtyButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("古琴调音", for: .normal)
        v.setImage(UIImage(resource: .gqyd), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        v.setTitleColor(UIColor(0x0F0F0F), for: .normal)
        v.setTitleColor(UIColor(0x0F0F0F).withAlphaComponent(0.6), for: .highlighted)
        v.takeImageAboveTitle(8)
        v.addTarget(self, action: #selector(onClickButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var jpqButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("节拍器", for: .normal)
        v.setImage(UIImage(resource: .jpq), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        v.setTitleColor(UIColor(0x0F0F0F), for: .normal)
        v.setTitleColor(UIColor(0x0F0F0F).withAlphaComponent(0.6), for: .highlighted)
        v.takeImageAboveTitle(8)
        v.addTarget(self, action: #selector(onClickButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var gqxxButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("古琴学习", for: .normal)
        v.setImage(UIImage(resource: .gqxx), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        v.setTitleColor(UIColor(0x0F0F0F), for: .normal)
        v.setTitleColor(UIColor(0x0F0F0F).withAlphaComponent(0.6), for: .highlighted)
        v.takeImageAboveTitle(8)
        v.addTarget(self, action: #selector(onClickButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var gywmButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("最新动态", for: .normal)
        v.setImage(UIImage(resource: .gywm), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        v.setTitleColor(UIColor(0x0F0F0F), for: .normal)
        v.setTitleColor(UIColor(0x0F0F0F).withAlphaComponent(0.6), for: .highlighted)
        v.takeImageAboveTitle(8)
        v.addTarget(self, action: #selector(onClickButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var webTitleLabel: UILabel = {
        let v = UILabel()
        v.text = "习琴心得"
        v.textColor = UIColor(0x0F0F0F)
        v.font = UIFont.boldSystemFont(ofSize: 15)
        return v
    }()
    
    private let webView = WKWebView()
    
    private var headerHeight: CGFloat = 300
    
    private let manager = NetworkReachabilityManager(host: "www.baidu.com")
    
    private let activityIndicatorView = UIActivityIndicatorView(style: .medium)
    
    private var guqinxuexiURL: URL?
}

extension HomeViewController {
    
    private func initializeSubviews() {
        view.backgroundColor = .white
        
        view.addSubview(naviHeaderView)
        naviHeaderView.snp.makeConstraints { make in
            make.height.equalTo(view.safeAreaInsets.top + 44)
            make.left.right.top.equalTo(0)
        }
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(naviHeaderView.snp.bottom)
            make.leading.trailing.bottom.equalTo(0)
        }
        
        scrollView.addSubview(headerView)
        
        headerHeight = 202 / 345.0 * (UIScreen.main.bounds.size.width - 30)
        headerView.addSubview(bannerImageView)
        bannerImageView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(headerHeight)
        }
        
        let space = floor(((UIScreen.main.bounds.size.width - 40) - 85 * 4) / 3.0)
        headerView.addSubview(gqtyButton)
        gqtyButton.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.height.equalTo(60)
            make.width.equalTo(85)
            make.top.equalTo(bannerImageView.snp.bottom).offset(20)
        }
        
        headerView.addSubview(jpqButton)
        jpqButton.snp.makeConstraints { make in
            make.left.equalTo(gqtyButton.snp.right).offset(space)
            make.height.equalTo(60)
            make.width.equalTo(85)
            make.centerY.equalTo(gqtyButton)
        }
        
        headerView.addSubview(gqxxButton)
        gqxxButton.snp.makeConstraints { make in
            make.left.equalTo(jpqButton.snp.right).offset(space)
            make.height.equalTo(60)
            make.width.equalTo(85)
            make.centerY.equalTo(gqtyButton)
        }
        
        headerView.addSubview(gywmButton)
        gywmButton.snp.makeConstraints { make in
            make.left.equalTo(gqxxButton.snp.right).offset(space)
            make.height.equalTo(60)
            make.width.equalTo(85)
            make.centerY.equalTo(gqtyButton)
        }
        
        headerView.addSubview(webTitleLabel)
        webTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(15.5)
            make.bottom.equalTo(-12)
        }
        
        headerHeight += 120
        headerView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.width.equalTo(scrollView.snp.width)
            make.height.equalTo(headerHeight)
        }
        
        webView.navigationDelegate = self
        webView.scrollView.isScrollEnabled = false
        scrollView.addSubview(webView)
        webView.frame = CGRect(x: 15, y: headerHeight, width: UIScreen.main.bounds.size.width - 30, height: 1)
        
        webView.addSubview(activityIndicatorView)
        activityIndicatorView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(40)
        }
        
        self.scrollView.contentSize = CGSize(width: self.view.frame.width, height: view.frame.height)
        
        manager?.startListening(onUpdatePerforming: { [weak self] status in
            switch status {
            case .notReachable:
                break
            case .unknown:
                break
            default:
                if App.shared.aboutInfo == nil {
                    self?.requestAboutMe()
                    self?.requestMusics()
                }
                self?.requestGuqinxuexiURL()
                self?.requestHomeBanner()
                self?.requestHomeWeb()
                self?.manager?.stopListening()
            }
        })
        
        if let value = UserDefaults.standard.object(forKey: "kHomeBannerImage") as? String {
            self.bannerImageView.sd_setImage(with: URL(string: value), placeholderImage: UIImage(resource: .banner))
        }
    }
    
    private func requestHomeWeb() {
        let url = URL(string: "http://tiaoyin.dyxt.net/du1/system/commonConfig/getWebInfo")!
        AF.request(url).response { [weak self] response in
            guard let `self` = self else { return }
            guard let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                return
            }
            if let dict = json["data"] as? [String: Any] {
                let accessUrl = dict["accessUrl"] as? String
                if let url = URL(string: accessUrl ?? "") {
                    let request = URLRequest(url: url)
                    self.webView.load(request)
                }
            }
        }
    }
    
    private func requestGuqinxuexiURL() {
        let url = URL(string: "http://tiaoyin.dyxt.net/du1/system/commonConfig/getMenuBtn")!
        AF.request(url).response { [weak self] response in
            guard let `self` = self else { return }
            guard let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                return
            }
            if let dict = json["data"] as? [String: Any] {
                let accessUrl = dict["accessUrl"] as? String
                if let url = URL(string: accessUrl ?? "") {
                    self.guqinxuexiURL = url
                }
            }
        }
    }
    
    private func requestHomeBanner() {
        let url = URL(string: "http://tiaoyin.dyxt.net/du1/system/commonConfig/getTop")!
        AF.request(url).response { [weak self] response in
            guard let `self` = self else { return }
            guard let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                return
            }
            if let dict = json["data"] as? [String: Any] {
                let accessUrl = dict["accessUrl"] as? String
                if let url = URL(string: accessUrl ?? "") {
                    DispatchQueue.main.async {
                        self.bannerImageView.sd_setImage(with: url)
                        UserDefaults.standard.set(url.absoluteString, forKey: "kHomeBannerImage")
                        UserDefaults.standard.synchronize()
                    }
                }
            }
        }
    }
    
    private func requestAboutMe() {
        AF.request(App.kAboutURL).response { response in
            guard let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                return
            }
            if let dict = json["data"] as? [String: Any] {
                App.shared.aboutInfo = dict["aboutInfo"] as? String
                App.shared.officialInfo = dict["officialInfo"] as? String
                App.shared.contactInfo = dict["contactInfo"] as? String
                if let html = App.shared.aboutInfo {
                    attributedStringFromHTML(html)
                }
                if let html = App.shared.officialInfo {
                    attributedStringFromHTML(html)
                }
                if let html = App.shared.contactInfo {
                    attributedStringFromHTML(html)
                }
            }
        }
    }
    
    private func requestMusics() {
        AF.request(App.kAllMusic).response { [weak self] response in
            guard let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
                return
            }
            let _ = json.map({
                if let id = $0["id"] as? String, let filename = $0["filename"] as? String, let urlStr = $0["accessUrl"] as? String {
                    if let url = URL(string: urlStr) {
                        FileManagerHelper.shared.downloadFile(from: url) { result in
                            switch result {
                            case .success(let success):
                                App.shared.cachedMusics[url] = success
                            case .failure(let failure):
                                break
                            }
                        }
                    }
                }
            })
        }
    }
    
    @objc private func onClickButton(_ sender: UIButton) {
        switch sender {
        case gqtyButton:
            let vc = TiaoyinViewController()
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        case jpqButton:
            let vc = JiepaiViewController()
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        case gqxxButton:
            guard let url = self.guqinxuexiURL else {
                requestGuqinxuexiURL()
                return
            }
            let vc = WebViewController(title: "古琴学习", url: url)
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        case gywmButton:
            guard let htmlString = App.shared.aboutInfo else { return }
            let vc = HTMLViewController(HTMLString: htmlString)
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        default:
            break
        }
    }
}

extension HomeViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicatorView.stopAnimating()
        self.webView.frame.size.height = 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            let newHeight = webView.scrollView.contentSize.height
            self.webView.frame.size.height = newHeight
            self.scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.headerHeight + newHeight)
        }
    }
}
